<?php
// +----------------------------------------------------------------------
// | NewThink [ Think More,Think Better! ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2018 http://www.newthink.cc All rights reserved.
// +----------------------------------------------------------------------
// | 版权所有：山西创泰网络科技有限公司
// +----------------------------------------------------------------------
// | Author: 子弹兄  Date:2019-03-08 Time:15:40
// +----------------------------------------------------------------------

namespace app\api\controller;

class CompanyIndustryMonitor extends BaseController
{
    
    /**
     * 查询工况分数据 (脱硫、脱硝)
     * @author Naomi
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function getCompanyIndustryMonitorMinute()
    {
        $param         = $this->request->param();
        $param['type'] = $param['type'] ?? 0;
        $db            = ['company_industry_monitor_sulfur_minute', 'company_industry_monitor_nitre_minute'];
        $field         = [
            [
                '_id' => 0,
                'publish_time' => 1,
                'company_id' => 1,
                'company_name' => 1,
                'drain_id' => 1,
                'drain_name' => 1,
                'facility_id' => 1,
                'facility_name' => 1,
                'operation_concentration' => 1,
                'operating_efficiency' => 1,
                'calcium_sulfur_ratio' => 1,
                'liquid_gas_ratio' => 1,
                'pulp_supply' => 1,
                'ph' => 1,
                'circulating_pump1_witching_stateX' => 1,
                'circulating_pump2_witching_stateX' => 1,
                'circulating_pump3_witching_stateX' => 1,
                'circulating_pump4_witching_stateX' => 1,
                'power' => 1,
            ],
            [
                '_id' => 0,
                'publish_time' => 1,
                'company_id' => 1,
                'company_name' => 1,
                'drain_id' => 1,
                'drain_name' => 1,
                'facility_id' => 1,
                'facility_name' => 1,
                'operation_concentration' => 1,
                'operating_efficiency' => 1,
                'nh3_flow' => 1,
                'out_nh3' => 1,
                'power' => 1,
            ]
        ];
        
        
        if (empty($param['start_time']) || empty($param['end_time'])) {
            //查询最新数据时间
            $query        = new \MongoDB\Driver\Query([], [
                'projection' => [
                    '_id' => 0,
                    'publish_time' => 1,
                ],
                'sort' => [
                    'publish_time' => -1
                ],
                'limit' => 1
            ]);
            $manager      = new \MongoDB\Driver\Manager('mongodb://root:Ws4815115!@dds-bp1babc036f87d64-pub.mongodb.rds.aliyuncs.com:3717');
            $publish_time = $manager->executeQuery("huanxin.{$db[$param['type']]}", $query)->toArray();
            
            empty($publish_time) && $this->success('成功', []);
            
            $publish_time = $publish_time[0]->publish_time;
            $start_time   = date('Y-m-d H:i:00', strtotime($publish_time));
            $end_time     = date('Y-m-d H:i:59', strtotime($publish_time));
        } else {
            $start_time = date('Y-m-d H:i:s', strtotime($param['start_time']));
            $end_time = date('Y-m-d H:i:s', strtotime($param['end_time']));
        }
        
        $filter = [
            'publish_time' => [
                '$gte' => $start_time,
                '$lte' => $end_time
            ]
        ];
        
        if (!empty($param['company_id'])) {
            $filter['company_id'] = (int)$param['company_id'];
        }
        
        if (!empty($param['drain_id'])) {
            $filter['drain_id'] = (int)$param['drain_id'];
        }
        
        if (!empty($param['facility_id'])) {
            $filter['facility_id'] = (int)$param['facility_id'];
        }
        
        if (!empty($param['industry_id'])) {
            $filter['industry_id'] = (int)$param['industry_id'];
        }
        
        if (isset($param['operating_efficiency_start'])) {
            $filter['operating_efficiency'] = ['$gte' => (int)$param['operating_efficiency_start']];
        }
        
        if (isset($param['operating_efficiency_end'])) {
            if (isset($filter['operating_efficiency'])) {
                $filter['operating_efficiency']['$lte'] = (int)$param['operating_efficiency_end'];
            } else {
                $filter = ['operating_efficiency' => ['$lte' => (int)$param['operating_efficiency_end']]];
            }
        }
        $options = [
            'projection' => $field[$param['type']],
            'sort' => [
                'publish_time' => 1
            ],
        ];
        
        //查询数据
        $query   = new \MongoDB\Driver\Query($filter, $options);
        $manager = new \MongoDB\Driver\Manager('mongodb://root:Ws4815115!@dds-bp1babc036f87d64-pub.mongodb.rds.aliyuncs.com:3717');
        $cursor  = $manager->executeQuery("huanxin.{$db[$param['type']]}", $query)->toArray();
        
        $data = ['table' => []];
        foreach ($cursor as $key => &$value) {
            $value = (array) $value;
            isset($value['circulating_pump1_witching_stateX']) && $value['circulating_pump1_witching_state'] = $value['circulating_pump1_witching_stateX'];
            isset($value['circulating_pump2_witching_stateX']) && $value['circulating_pump2_witching_state'] = $value['circulating_pump2_witching_stateX'];
            isset($value['circulating_pump3_witching_stateX']) && $value['circulating_pump3_witching_state'] = $value['circulating_pump3_witching_stateX'];
            isset($value['circulating_pump4_witching_stateX']) && $value['circulating_pump4_witching_state'] = $value['circulating_pump4_witching_stateX'];
            if ($value['power'] === 0) {
                $data['table'][] = array_map(function($v){
                    is_double($v) && $v = "-";
                    return $v;
                }, $value);
                unset($cursor[$key]);
            } else {
                $value['operation_concentration'] = round($value['operation_concentration'], 1);
                $value['operating_efficiency']    = round($value['operating_efficiency'] * 100, 1);
                
                $data['operation_concentration']['date'][]    = $value['publish_time'];
                $data['operation_concentration']['data'][0][] = $value['operation_concentration'];
                $data['operating_efficiency']['date'][]       = $value['publish_time'];
                $data['operating_efficiency']['data'][0][]    = $value['operating_efficiency'];
                
                
                if ($param['type'] == 0) {

                    $value['calcium_sulfur_ratio']    = round($value['calcium_sulfur_ratio'], 2);
                    $value['liquid_gas_ratio']    = round($value['liquid_gas_ratio'], 2);
                    $value['pulp_supply']    = round($value['pulp_supply'], 2);
                    $value['ph']    = round($value['ph'], 2);
    
                    $data['calcium_sulfur_ratio']['date'][]    = $value['publish_time'];
                    $data['calcium_sulfur_ratio']['data'][0][] = $value['calcium_sulfur_ratio'];
                    $data['liquid_gas_ratio']['date'][]        = $value['publish_time'];
                    $data['liquid_gas_ratio']['data'][0][]     = $value['liquid_gas_ratio'];
                    
                } else if ($param['type'] == 1) {
                    $value['nh3_flow']    = round($value['nh3_flow'], 2);
                    $value['out_nh3']    = round($value['out_nh3'], 2);
                    
                    $data['nh3_flow']['date'][]    = $value['publish_time'];
                    $data['nh3_flow']['data'][0][] = $value['nh3_flow'];
                }
                $data['table'][] = $value;
            }
        }
    
        if (empty($cursor)) {
            $startH = date('H', strtotime($start_time));
            $endH   = date('H', strtotime($end_time));
            $dates  = self::getDateFromRange($start_time, $end_time);
            foreach ($dates['dates'] as $k => $v) {
                for ($i = 0; $i < 24; $i++) {
                    if (($k == 0 && $i < $startH) || ($k == (count($dates['dates']) - 1) && $i > $endH)) {
                        continue;
                    }
                    $data['operation_concentration']['date'][] = date("Y-m-d $i:00:00", strtotime($v));
                    $data['operating_efficiency']['date'][]    = date("Y-m-d $i:00:00", strtotime($v));
                    if (empty($param['type'])) {
                        $data['calcium_sulfur_ratio']['date'][] = date("Y-m-d $i:00:00", strtotime($v));
                        $data['liquid_gas_ratio']['date'][]     = date("Y-m-d $i:00:00", strtotime($v));
                    } else {
                        $data['nh3_flow']['date'][] = date("Y-m-d $i:00:00");
                    }
                }
            }
        
            $data['operation_concentration']['data'] = [];
            $data['operating_efficiency']['data']    = [];
            if (empty($param['type'])) {
                $data['calcium_sulfur_ratio']['data'] = [];
                $data['calcium_sulfur_ratio']['data'] = [];
            } else {
                $data['nh3_flow']['data'] = [];
            }
        }
        
        $this->success('成功', $data);
    }
    
    /**
     * 查询工况时数据 (脱硫、脱硝)
     * @author Naomi
     */
    public function getCompanyIndustryMonitorHour()
    {
        $param         = $this->request->param();
        $param['type'] = $param['type'] ?? 0;#类型,默认脱硫
        empty($param['start_time']) && $param['start_time'] = date('Y-m-d 00:00:00');
        empty($param['end_time']) && $param['end_time'] = date('Y-m-d H:00:00');
        
        $db    = ['company_industry_monitor_sulfur_hour', 'company_industry_monitor_nitre_hour'];
        $field = ['power,publish_time,facility_name,ROUND(operation_concentration, 1) operation_concentration,ROUND(operating_efficiency * 100, 1) operating_efficiency,ROUND(calcium_sulfur_ratio, 2) calcium_sulfur_ratio,ROUND(liquid_gas_ratio, 2) liquid_gas_ratio,ROUND(pulp_supply, 2) pulp_supply,ROUND(ph, 2) ph,circulating_pump1_witching_state,circulating_pump2_witching_state,circulating_pump3_witching_state,circulating_pump4_witching_state', 'power,publish_time,facility_name,ROUND(operation_concentration, 1) operation_concentration,ROUND(operating_efficiency * 100, 1) operating_efficiency,ROUND(nh3_flow, 2) nh3_flow,ROUND(out_nh3, 2) out_nh3'];
        
        $where = "(publish_time between '{$param['start_time']}' AND  '{$param['end_time']}')";
        
        if (!empty($param['company_id'])) {
            if (!empty($where)) {
                $where .= " AND ";
            }
            $where .= "company_id = {$param['company_id']}";
        }
        
        if (!empty($param['drain_id'])) {
            if (!empty($where)) {
                $where .= " AND ";
            }
            $where .= "drain_id = {$param['drain_id']}";
        }
        
        if (!empty($param['facility_id'])) {
            if (!empty($where)) {
                $where .= " AND ";
            }
            $where .= "facility_id = {$param['facility_id']}";
        }
        !empty($where) && $where = "WHERE $where";
        
        $dsn      = 'mysql:host=rm-bp11r52xk5623pn66o.mysql.rds.aliyuncs.com;dbname=huanxin';
        $userName = 'huanxin';
        $passWord = 'Sxctkjhuanxin!';
        $pdo      = new \PDO($dsn, $userName, $passWord);
        $pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
        
        $sql = "SELECT {$field[$param['type']]} FROM `{$db[$param['type']]}` {$where} ORDER BY `publish_time` ASC";
        $stmt = $pdo->query($sql) or $this->error($pdo->errorInfo()[2]);
        $tableData = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        
        $data = ['table' => []];
        
        foreach ($tableData as $key => $value) {
            if ($value['power'] == -1) {
                #数据无效,只进行展示基础数据
    
                $complementField = ['operation_concentration', 'operating_efficiency', 'inlet_gas_volume', 'aig_flue_flow'];
                foreach ($value as $k => $v) {
                    $d[$k] = (is_numeric($v) && !in_array($k, $complementField)) ? '-' : $v;
                }
                $data['table'][] = $d;
                
                $data['operation_concentration']['date'][]    = $value['publish_time'];
                $data['operation_concentration']['data'][0][] = $value['operation_concentration'];
                $data['operating_efficiency']['date'][]       = $value['publish_time'];
                $data['operating_efficiency']['data'][0][]    = $value['operating_efficiency'];
//                unset($tableData[$key]);
            } else if ($value['power'] == 1) {
                #数据正常,组合趋势图
                $data['table'][] = $value;
    
                $data['operation_concentration']['date'][]    = $value['publish_time'];
                $data['operation_concentration']['data'][0][] = $value['operation_concentration'];
                $data['operating_efficiency']['date'][]       = $value['publish_time'];
                $data['operating_efficiency']['data'][0][]    = $value['operating_efficiency'];
                if (empty($param['type'])) {
                    $data['calcium_sulfur_ratio']['date'][]    = $value['publish_time'];
                    $data['calcium_sulfur_ratio']['data'][0][] = $value['calcium_sulfur_ratio'];
                    $data['liquid_gas_ratio']['date'][]        = $value['publish_time'];
                    $data['liquid_gas_ratio']['data'][0][]     = $value['liquid_gas_ratio'];
                } else {
                    $data['nh3_flow']['date'][]    = $value['publish_time'];
                    $data['nh3_flow']['data'][0][] = $value['nh3_flow'];
                }
            }
        }
        
        #判断是否无数据
        if (empty($tableData)) {
            #组合趋势图时间
            $startH = date('H', strtotime($param['start_time']));
            $endH   = date('H', strtotime($param['end_time']));
            $dates  = self::getDateFromRange($param['start_time'], $param['end_time']);
            foreach ($dates['dates'] as $k => $v) {
                for ($i = 0; $i < 24; $i++) {
                    if (($k == 0 && $i < $startH) || ($k == (count($dates['dates']) - 1) && $i > $endH)) {
                        continue;
                    }
                    $data['operation_concentration']['date'][] = date("Y-m-d $i:00:00", strtotime($v));
                    $data['operating_efficiency']['date'][]    = date("Y-m-d $i:00:00", strtotime($v));
                    if (empty($param['type'])) {
                        $data['calcium_sulfur_ratio']['date'][] = date("Y-m-d $i:00:00", strtotime($v));
                        $data['liquid_gas_ratio']['date'][]     = date("Y-m-d $i:00:00", strtotime($v));
                    } else {
                        $data['nh3_flow']['date'][] = date("Y-m-d $i:00:00");
                    }
                }
            }
            #插入趋势图空数据
            $data['operation_concentration']['data'] = [];
            $data['operating_efficiency']['data']    = [];
            if (empty($param['type'])) {
                $data['calcium_sulfur_ratio']['data'] = [];
                $data['calcium_sulfur_ratio']['data'] = [];
            } else {
                $data['nh3_flow']['data'] = [];
            }
        }
        
        $this->success('成功', $data);
    }
    
    /**
     * 查询工况天数据 (脱硫、脱硝)
     * @author Naomi
     */
    public function getCompanyIndustryMonitorDay()
    {
        $param         = $this->request->param();
        $param['type'] = $param['type'] ?? 0;
        
        empty($param['facility_id']) && $param['type'] == 0 && $param['facility_id'] = 3;
        empty($param['facility_id']) && $param['type'] == 1 && $param['facility_id'] = 5;
        
        empty($param['start_time']) && $param['start_time'] = date('Y-m-d 00:00:00', strtotime('-7 day'));
        empty($param['end_time']) && $param['end_time'] = date('Y-m-d 00:00:00', strtotime('-1 day'));
        
        $db    = ['company_industry_monitor_sulfur_day', 'company_industry_monitor_nitre_day'];
        $field = ['power,publish_time,facility_name,ROUND(operation_concentration, 1) operation_concentration,ROUND(operating_efficiency * 100 , 1) operating_efficiency,ROUND(calcium_sulfur_ratio, 2) calcium_sulfur_ratio,ROUND(liquid_gas_ratio, 2) liquid_gas_ratio,ROUND(pulp_supply, 2) pulp_supply,ROUND(ph, 2) ph,circulating_pump1_witching_state,circulating_pump2_witching_state,circulating_pump3_witching_state,circulating_pump4_witching_state', 'power,publish_time,facility_name,ROUND(operation_concentration, 1) operation_concentration,ROUND(operating_efficiency * 100, 1) operating_efficiency,ROUND(nh3_flow, 2) nh3_flow,ROUND(out_nh3, 2) out_nh3'];
        
        $where = "(publish_time between '{$param['start_time']}' AND  '{$param['end_time']}')";
        
        if (!empty($param['industry_id'])) {
            !empty($where) && $where .= " AND ";
            
            $where .= "industry_id = {$param['industry_id']}";
        }
        
        if (!empty($param['company_id'])) {
            !empty($where) && $where .= " AND ";
            
            $where .= "company_id = {$param['company_id']}";
        }
        
        if (!empty($param['drain_id'])) {
            !empty($where) && $where .= " AND ";
            
            $where .= "drain_id = {$param['drain_id']}";
        }
        
        if (!empty($param['facility_id'])) {
            !empty($where) && $where .= " AND ";
            
            $where .= "facility_id = {$param['facility_id']}";
        }
        
        !empty($where) && $where = "WHERE $where";
        
        $dsn      = 'mysql:host=rm-bp11r52xk5623pn66o.mysql.rds.aliyuncs.com;dbname=huanxin';
        $userName = 'huanxin';
        $passWord = 'Sxctkjhuanxin!';
        $pdo      = new \PDO($dsn, $userName, $passWord);
        $pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
        
        $sql = "SELECT {$field[$param['type']]} FROM `{$db[$param['type']]}` {$where} ORDER BY `publish_time` ASC";
        $stmt = $pdo->query($sql) or $this->error($pdo->errorInfo()[2]);
        $tableData = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        
        $data = ['table' => []];
        
        foreach ($tableData as $key => $value) {
            if ($value['power'] == -1) {
                #数据无效,值进行展示基础数据
                $data['table'][] = array_map(function ($v) {
                    is_numeric($v) && $v = "-";
                    return $v;
                }, $value);
                unset($tableData[$key]);
            } else if ($value['power'] == 1) {
                #数据正常,组合趋势图
                $data['table'][] = $value;
        
                $data['operation_concentration']['date'][]    = $value['publish_time'];
                $data['operation_concentration']['data'][0][] = $value['operation_concentration'];
                $data['operating_efficiency']['date'][]       = $value['publish_time'];
                $data['operating_efficiency']['data'][0][]    = $value['operating_efficiency'];
                if (empty($param['type'])) {
                    $data['calcium_sulfur_ratio']['date'][]    = $value['publish_time'];
                    $data['calcium_sulfur_ratio']['data'][0][] = $value['calcium_sulfur_ratio'];
                    $data['liquid_gas_ratio']['date'][]        = $value['publish_time'];
                    $data['liquid_gas_ratio']['data'][0][]     = $value['liquid_gas_ratio'];
                } else {
                    $data['nh3_flow']['date'][]    = $value['publish_time'];
                    $data['nh3_flow']['data'][0][] = $value['nh3_flow'];
                }
            }
        }
        
        #判断是否无数据,
        if (empty($tableData)) {
            #组合趋势图时间
            $days = self::getDateFromRange($param['start_time'], $param['end_time']);
            foreach ($days['dates'] as $v) {
                $data['operation_concentration']['date'][] = $v;
                $data['operating_efficiency']['date'][]    = $v;
                if (empty($param['type'])) {
                    $data['calcium_sulfur_ratio']['date'][] = $v;
                    $data['liquid_gas_ratio']['date'][]     = $v;
                } else {
                    $data['nh3_flow']['date'][] = $v;
                }
            }
            
            #插入趋势图空数据
            $data['operation_concentration']['data'] = [];
            $data['operating_efficiency']['data']    = [];
            if (empty($param['type'])) {
                $data['calcium_sulfur_ratio']['data'] = [];
                $data['calcium_sulfur_ratio']['data'] = [];
            } else {
                $data['nh3_flow']['data'] = [];
            }
        }
        
        $this->success('成功', $data);
    }
    
    /**
     * 获取指定日期段内每一天的日期和天数
     * @param string $startDate 开始日期 格式化时间 Y-m-d H:i:s
     * @param string $endDate 结束日期 格式化时间 Y-m-d H:i:s
     * @return array
     */
    public static function getDateFromRange($startDate, $endDate)
    {
        $startDate  = date('Y-m-d 00:00:00', strtotime($startDate));
        $endDate    = date('Y-m-d 23:59:59', strtotime($endDate));
        $sTimestamp = strtotime($startDate);
        $eTimestamp = strtotime($endDate);
        if ($eTimestamp < $sTimestamp) return [];
        // 计算日期段内有多少天
        $days = (int)ceil(($eTimestamp - $sTimestamp) / 86400);
        // 保存每天日期
        $date = array();
        for ($i = 0; $i < $days; $i++) {
            $date[] = date('Y-m-d', $sTimestamp + (86400 * $i));
        }
        $data = [
            'dates' => $date,
            'days' => $days,
        ];
        return $data;
    }
    
    /**
     * 工况组态图接口
     * @author JiYun On 2019/07/01
     */
    public function getIndustryData()
    {
        $param = $this->request->param();
        
        $type       = $param['type'];
        $companyId  = $param['company_id'];
        $drainId    = $param['drain_id'];
        $facilityId = $param['facility_id'];
        
        $dsn      = 'mysql:host=rm-bp11r52xk5623pn66o.mysql.rds.aliyuncs.com;dbname=huanxin';
        $userName = 'huanxin';
        $passWord = 'Sxctkjhuanxin!';
        $pdo      = new \PDO($dsn, $userName, $passWord);
        $pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
        
        // 获取企业ID对应的营业执照后四位
        $fmt     = "SELECT license_number_simple FROM `basic_company` where id = %d";
        $sql     = sprintf($fmt, $companyId);
        $stmt    = $pdo->query($sql);
        $company = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        
        if (!isset($company[0]['license_number_simple'])) {
            $this->error('无效的企业ID');
        }
        
        // 获取企业ID和排口ID对应的排口编号
        $fmt   = "SELECT data_from_paikoubianhao FROM `basic_drain` WHERE id = %d and company_id = %d";
        $sql   = sprintf($fmt, $drainId, $companyId);
        $stmt  = $pdo->query($sql);
        $drain = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        
        if (!isset($drain[0]['data_from_paikoubianhao'])) {
            $this->error('无效的排口ID');
        }
        
        $data = [];
        
        $filter = [
            'qiyeID' => $company[0]['license_number_simple'],
            'paikoubianhao' => (String)$drain[0]['data_from_paikoubianhao']
        ];
        
        $projection = [];
        
        $len = 0;
        
        // 1 为脱硝
        if ($type == 1) {
            $m = 0;
            $n = 0;
            
            switch ($facilityId) {
                case 1:
                    $m = '1';
                    $n = 'a';
                    break;
                case 2:
                    $m = '1';
                    $n = 'b';
                    break;
                case 4:
                    $m = '2';
                    $n = 'a';
                    break;
                case 5:
                    $m = '2';
                    $n = 'b';
                    break;
            }
            
            $projection = [
                // #SCR反应器出口烟气NH3浓度
                'SCRfanyingqichukouyanqiNH3nongdu_' . $m . '_' . $n => 1,
                // #1机组SCR反应器AAIG前烟道O2浓度
                'SCRfanyingqichukouyanqiO2nongdu_' . $m . '_' . $n => 1,
                // #1机组SCR反应器AAIG前烟道NO2浓度
                'SCRfanyingqichukouyanqiNOXnongdu_' . $m . '_' . $n => 1,
                // #1机组SCR反应器AAIG前烟道温度
                'SCRfanyingqichukouyanqiwendu_' . $m . '_' . $n => 1,
                // 烟气压差
                'fanyingqiXyanqiyacha1_' . $m . '_' . $n => 1,
                // 烟气压差
                'fanyingqiXyanqiyacha2_' . $m . '_' . $n => 1,
                // 烟气压差
                'fanyingqiXyanqiyacha3_' . $m . '_' . $n => 1,
                // 氨气流量
                'anqiliuliang_' . $m . '_' . $n => 1,
                // #1机组SCR反应器AAIG前烟道流量
                'SCRfanyingqiXAIGqianyandaoliuliang_' . $m . '_' . $n => 1,
                // #1机组SCR反应器AAIG前烟道O2浓度
                'SCRfanyingqiXAIGqianyandaoO2nongdu_' . $m . '_' . $n => 1,
                // #1机组SCR反应器AAIG前烟道NO2浓度
                'SCRfanyingqiXAIGqianyandaoyanqiNOXnongdu_' . $m . '_' . $n => 1,
                // #1机组SCR反应器AAIG前烟道温度
                'SCRfanyingqiXjinkouyanqiwendu1_' . $m . '_' . $n => 1,
                'insert_time' => 1
            ];
            
            $len = 4;
        } elseif ($type == 0) {
            // 0 为脱硫
            $m = 0;
            
            if ($facilityId == 3) {
                $m = 1;
            } elseif ($facilityId == 6) {
                $m = 2;
            }
            
            $projection = [
                // #1脱硫净烟气流量
                'chukouyanqiliang_' . $m => 1,
                // #1脱硫净烟气O2浓度
                'chukouO2nongdu_' . $m => 1,
                // #1脱硫净烟气SO2浓度
                'chukouliunongdu_' . $m => 1,
                // #1脱硫净烟气粉尘浓度
                'chukouyanqifenchendu_' . $m => 1,
                // #1脱硫净烟气湿度
                'chukouyanqishidu_' . $m => 1,
                // #1脱硫净烟气压力
                'chukouyanqiyali_' . $m => 1,
                // #1脱硫净烟气温度
                'chukouyanwen_' . $m => 1,
                
                // #1脱硫原烟气流量
                'rukouyanqiliang_' . $m => 1,
                // #1脱硫原烟气O2浓度
                'rukouO2nongdu_' . $m => 1,
                // #1脱硫原烟气SO2浓度
                'rukouliunongdu_' . $m => 1,
                // #1脱硫原烟气粉尘浓度
                'rukouyanqifenchendu_' . $m => 1,
                // #1脱硫原烟气湿度
                'rukouyanqishidu_' . $m => 1,
                // #1脱硫原烟气压力
                'rukouyanqiyali_' . $m => 1,
                // #1脱硫原烟气温度
                'rukouyanwen_' . $m => 1,
                
                // 石灰浆液浓度
                'shihuishijiangyemidu_' . $m => 1,
                // 石灰浆液流量
                'shihuishigongjiangliang_' . $m => 1,
                
                // 氧化风机2号电流
                'no2yanghuafengjidianliu_' . $m => 1,
                // 氧化风机1号电流
                'no1yanghuafengjidianliu_' . $m => 1,
                
                // 石灰浆液入口#1电流
                'no1xunhuanbengdianliu_' . $m => 1,
                // 石灰浆液入口#1电流
                'no2xunhuanbengdianliu_' . $m => 1,
                // 石灰浆液入口#1电流
                'no3xunhuanbengdianliu_' . $m => 1,
                // 石灰浆液入口#1电流
                'no4xunhuanbengdianliu_' . $m => 1,
                
                // PH值
                'PHzhi_' . $m => 1,
                
                'insert_time' => 1
            ];
            
            $len = 2;
        }
        
        $options['projection'] = $projection;
        // 倒序
        $options['sort'] = ['insert_time' => -1];
        // 取1条
        $options['limit'] = 1;
        
        // 查询数据
        try {
            $query   = new \MongoDB\Driver\Query($filter, $options);
            $manager = new \MongoDB\Driver\Manager(
                'mongodb://root:Ws4815115!@dds-bp1babc036f87d64-pub.mongodb.rds.aliyuncs.com:3717'
            );
            $data    = $manager
                ->executeQuery("huanxin.source_company_jin_neng_re_dian", $query)
                ->toArray();
            
            if (count($data) === 0) {
                $this->error('数据为空，请检查查询条件');
            }
            
            $result = [];
            
            foreach ($data[0] as $key => $value) {
                // 四舍五入
                is_numeric($value) && $value = round($value, 2);
                // 去掉key中的编号
                $k = substr($key, 0, strlen($key) - $len);
                // 电流相关的值进行取整
                if ($k == 'no1xunhuanbengdianliu'
                    || $k == 'no2xunhuanbengdianliu'
                    || $k == 'no3xunhuanbengdianliu'
                    || $k == 'no4xunhuanbengdianliu'
                    || $k == 'no1yanghuafengjidianliu'
                    || $k == 'no2yanghuafengjidianliu') {
                    $value = floor($value);
                }
                
                $result[$k] = $value;
            }
            
            $data = $result;
        } catch (\MongoDB\Driver\Exception\Exception $e) {
            $this->error($e->getMessage());
        }
        
        $this->success('成功', $data);
    }
}
